package com.example.quanxin.service;/*
 *
 *   welcome:11311
 *   创建时间:2023/5/20
 *
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.quanxin.config.GlobalConfig;
import com.example.quanxin.entity.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import okhttp3.*;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.jsoup.nodes.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiService {

    public static Boolean getAndStoreCookies(LoginParam loginParam) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    Map<String, List<Cookie>> globalCookieMap = GlobalConfig.getGlobalCookieMap();
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        globalCookieMap.put("quanxin", cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = globalCookieMap.get("quanxin");
                        return cookies != null ? cookies : new ArrayList<>();
                    }
                })
                .build();

        RequestBody formBody = new FormBody.Builder()
                .add("fid", "-1")
                .add("uname", (loginParam != null && loginParam.getUsername() != null) ? loginParam.getUsername() : "nLK0yN6+CtzEvcbwjNI2sQ==")
                .add("password", (loginParam != null && loginParam.getPassword() != null) ? loginParam.getPassword(): "oRHI9TyKOXXMGWtTdLhfyQ==")
                .add("refer", "https://i.chaoxing.com")
                .add("t", "true")
                .add("forbidotherlogin", "0")
                .add("validate", "")
                .add("doubleFactorLogin", "0")
                .add("independentId", "0")
                .build();

        Request request = new Request.Builder()
                .url("https://passport2.chaoxing.com/fanyalogin")
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            log.info("response{}",response);
        }catch (Exception e){
            throw new RuntimeException("获取token失败");
        }


        return true;
    }
    static OkHttpClient client = new OkHttpClient.Builder()
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                    try {
//                        getAndStoreCookies(new LoginParam());
//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }
//                    globalCookieMap.put("quanxin", cookies);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = GlobalConfig.getCookies("quanxin");
                    return cookies != null ? cookies : new ArrayList<>();
                }
            })
            .build();

    public OkHttpClient anotherClient = new OkHttpClient.Builder().build();

    public JSONArray getActive(ActiveParam activeParam){
        RequestBody formBody = new FormBody.Builder()
                .add("fid", String.valueOf(activeParam.getFid()))
                .add("jclassId", String.valueOf(activeParam.getJclassId()))
                .add("courseId", String.valueOf(activeParam.getCourseId()))
                .add("status", String.valueOf(activeParam.getStatus()))
                .build();
        JSONObject result = null;
        Request request = new Request.Builder()
                .url("https://mobilelearn.chaoxing.com/widget/pcpick/main/getActiveList")
                .post(formBody)
                .build();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            log.info("返回结果为{}",string);
            result = JSON.parseObject(string);
            return result.getJSONObject("data").getJSONArray("actives");
        }catch (Exception e){
            log.info("错误信息为{}",e);
//            try {
//                getAndStoreCookies(new LoginParam());
//            } catch (IOException e1) {
//                throw new RuntimeException(e1);
//            }
            if (activeParam.getStatus().equals(0L)){
           String s= """
        [
        {
            "fid": null,
            "bsid": null,
            "viewPicPath": null,
            "scoreWeight": null,
            "starttime": 1716367251575,
            "source": 15,
            "oldActiveId": null,
            "grouptype": null,
            "createuidname": null,
            "clazzid": 98621823,
            "activeSort": 13,
            "id": 7000097184867,
            "credit": null,
            "newOld": null,
            "courseId": null,
            "jwCourseId": null,
            "longitude": null,
            "addToCacheTime": 0,
            "isclone": null,
            "createxxuid": "121378614",
            "chatid": "247640502632452",
            "ifaveraged": null,
            "sffxs": null,
            "sfdp": null,
            "sxs": null,
            "oldOtherId": null,
            "activeType": 35,
            "endtimes": null,
            "name": "默认任务(任务为空时展示)",
            "region": null,
            "status": 2,
            "isold": null,
            "ifsendmessage": null,
            "configJson": null,
            "ifcommit": 1,
            "normscore": null,
            "timeLong": 86400000,
            "ismark": null,
            "userStatus": null,
            "isbackfill": null,
            "stuid": null,
            "latitude": null,
            "currentversion": null,
            "pActiveId": null,
            "zhjsid": null,
            "signCode": null,
            "title": null,
            "parentid": 7000097184866,
            "content": "",
            "activityTranMode": null,
            "ifrefreshewm": null,
            "realActiveId": null,
            "pptPlanId": 7000005192038,
            "isresult": null,
            "attendNum": null,
            "isnorm": 1,
            "dpurl": null,
            "isbegins": null,
            "createtime": 1716367251000,
            "currentstatus": null,
            "ifphoto": null,
            "otherId": 243185166,
            "endtime": 1716453651575,
            "showhide": null,
            "userName": null,
            "endtimeStr": "2024-05-23 16:40:51",
            "releaseNum": 4,
            "pptnum": null,
            "url": null,
            "editconfig": null,
            "iphoneContent": null,
            "starttimeStr": "2024-05-22 16:40:51",
            "chartid": null,
            "jurl": null,
            "isanony": null,
            "createtimeStr": "2024-05-22 16:40:51",
            "starttimes": null,
            "isdelete": null,
            "updatetime": null,
            "attendPer": null,
            "ifgetrange": null,
            "islook": null,
            "createuid": "121378614",
            "mark": null
        }]
                    """;

            JSONArray jsonObject = JSON.parseArray(s);
            return jsonObject;}
            else {
                return JSON.parseArray("[]");
            }
//            throw new RuntimeException("获取列表错误");
        }
    }

    public List<GroupLivenessRatio> getGroupLivenessRatio(HistoryScore historyScore) throws Exception {
        List<Score> scoreList = getHistoryScore(historyScore);
        Map<String, GroupLivenessRatio> mapping = new HashMap<>();
        Map<String, Integer> count = new HashMap<>();
        for(Score score : scoreList){
            if(mapping.containsKey(score.getTaskGroupName())){
                GroupLivenessRatio liveness = mapping.get(score.getTaskGroupName());
                liveness.setLivenessRatio(liveness.getLivenessRatio() + score.getScore().intValue());
                count.put(score.getTaskGroupName(), count.get(score.getTaskGroupName()) + 1);
            } else {
                GroupLivenessRatio liveness = new GroupLivenessRatio();
                liveness.setGroupName(score.getTaskGroupName());
                liveness.setLivenessRatio(score.getScore().intValue());
                mapping.put(score.getTaskGroupName(), liveness);
                count.put(score.getTaskGroupName(), 1);
            }
        }

        List<GroupLivenessRatio> result = new ArrayList<>();
        for(Map.Entry<String, GroupLivenessRatio> entry : mapping.entrySet()){
            GroupLivenessRatio liveness = entry.getValue();
            liveness.setLivenessRatio(liveness.getLivenessRatio() / count.get(entry.getKey()));
            result.add(liveness);
        }
        OptionalDouble average = result.stream().mapToInt(GroupLivenessRatio::getLivenessRatio).average();
        for(GroupLivenessRatio groupLivenessRatio : result){
           if(groupLivenessRatio.getGroupName().trim().equals("奋进组")){
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/21cf1e45b89b41788985d3263511b295.jpg");
            }else if (groupLivenessRatio.getGroupName().trim().equals("数创组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/2c43f05a641544169286b19a2f58f76f.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数智组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/b737fdbe452a4f05951c779c46c98769.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数德组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/b737fdbe452a4f05951c779c46c98769.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数人组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/a228482f9dd24170b1cca583f532a9b3.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数探组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/000e2889601748c1a2336a351c86c9c8.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数心组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/af2b1f04300f464f82695391b966295c.png");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("数字组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/163a0e575ade4df68ba936dabe6c45e0.png");
            }else if (groupLivenessRatio.getGroupName().trim().equals("探索组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/96da7d4527a448c18cd46646e53fc923.jpg");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("腾飞组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/b7edf54041224f70a5f78c85e345f900.jpg");
            }
            else if (groupLivenessRatio.getGroupName().trim().equals("传承组")) {
                groupLivenessRatio.setImageUrl("https://file.pzhszgh.cn/union/outdoor/8851cb93eb56418f84803be63613d6d1.jpg");
            }
            else {
                groupLivenessRatio.setImageUrl("");
            }

            groupLivenessRatio.setLivenessRatio(groupLivenessRatio.getLivenessRatio() - (int) average.getAsDouble());
        }

        return result.stream().sorted(Comparator.comparing(GroupLivenessRatio::getLivenessRatio).reversed()).collect(Collectors.toList());
    }

    public List<GroupLiveness> getGroupLiveness(HistoryScore historyScore) throws Exception {
        List<Score> scoreList = getHistoryScore(historyScore);
        Map<String, GroupLiveness> mapping = new HashMap<>();
        Map<String, Integer> count = new HashMap<>();
        for(Score score : scoreList){
            if(mapping.containsKey(score.getTaskGroupName())){
                GroupLiveness liveness = mapping.get(score.getTaskGroupName());
                liveness.setTotalScore(liveness.getTotalScore() + score.getScore().intValue());
                count.put(score.getTaskGroupName(), count.get(score.getTaskGroupName()) + 1);
            } else {
                GroupLiveness liveness = new GroupLiveness();
                liveness.setGroupName(score.getTaskGroupName());
                liveness.setTotalScore(score.getScore().intValue());
                mapping.put(score.getTaskGroupName(), liveness);
                count.put(score.getTaskGroupName(), 1);
            }
        }

        List<GroupLiveness> result = new ArrayList<>();
        for(Map.Entry<String, GroupLiveness> entry : mapping.entrySet()){
            GroupLiveness liveness = entry.getValue();
            liveness.setLiveness(liveness.getTotalScore() / count.get(entry.getKey()));
            result.add(liveness);
        }
        return result.stream().sorted(Comparator.comparing(GroupLiveness::getLiveness).reversed()).collect(Collectors.toList());
    }

    public List<StudentLiveness> getStudentLiveness(StudentLivenessReq req) throws Exception {
        List<StudentLiveness> result = new ArrayList<>();
        for(int i = 1; i < 30; i ++){
            RequestBody formBody = new FormBody.Builder()
                    .add("courseId", String.valueOf(req.getCourseId()))
                    .add("classId", String.valueOf(req.getClassId()))
                    .add("identity", "s")
                    .add("pageNum", Integer.toString(i))
                    .build();
            Request request = new Request.Builder()
                    .url("https://mooc1-1.chaoxing.com/mooc-ans/moocAnalysis/bbsAnalysisData")
                    .post(formBody)
                    .build();
            try(Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                if(StringUtils.isEmpty(string)){
                    break;
                }
                result.addAll(parseHtmlTable(string));
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("获取列表错误");
            }
        }
        if ( result.isEmpty()){
            //如果没有数据则写死两个
            StudentLiveness studentLiveness=new StudentLiveness();
            studentLiveness.setLiveness(0);
            studentLiveness.setStudentName("牟孝杨");
            result.add(studentLiveness);
            StudentLiveness studentLiveness1=new StudentLiveness();
            studentLiveness1.setStudentName("谭春勇");
            studentLiveness1.setLiveness(0);
            result.add(studentLiveness1);
        }
        return result.stream().sorted(Comparator.comparing(StudentLiveness::getLiveness).reversed()).collect(Collectors.toList());
    }





    private Collection<? extends StudentLiveness> parseHtmlTable(String html) {
        List<StudentLiveness> result = new ArrayList<>();
        Document doc = Jsoup.parse(html);

        Elements rows = doc.select("tr");
        Integer total = 0;
        for (Element row : rows) {
            total++;
            Elements cols = row.select("td");
            if(total == 1){
                continue;
            }
            int i = 0;
            StudentLiveness studentLiveness = new StudentLiveness();
            for (Element col : cols) {
                if(i == 0){
                    String text = col.text();
                    if(StringUtils.isEmpty(text)){
                        break;
                    }
                    studentLiveness.setStudentName(text);
                }
                if(i == 1){
                    String text = col.text();
                    try {
                        studentLiveness.setLiveness(Integer.parseInt(text));
                    }catch (Exception e){
                        studentLiveness.setLiveness(0);
                    }
                }
                i ++;
                if(i > 1){
                    break;
                }
            }
            if(! StringUtils.isEmpty(studentLiveness.getStudentName())){
                result.add(studentLiveness);
            }

        }
        return result;
    }



    public List<Score> getHistoryScore(HistoryScore historyScore) throws Exception {
        List<Score> result = new ArrayList<>();
        if(CollectionUtils.isEmpty(historyScore.getActiveIdList())){
            return result;
        }
        Map<Long, Score> mapping = new HashMap<>();
        for(Long activeId : historyScore.getActiveIdList()){
            Request request = new Request.Builder()
                    .url("https://mobilelearn.chaoxing.com/v2/apis/task/getAllMembersByActiveId?activeId=" + activeId)
                    .build();
            try(Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                JSONObject jsonObject = JSON.parseObject(string);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("allGroupMembers");
                for(int i = 0; i < jsonArray.size(); i ++){
                    Score score = jsonArray.getJSONObject(i).toJavaObject(Score.class);
                    if(score.getScore() == null){
                        score.setScore(0.0);
                    }
                    if(mapping.containsKey(score.getUid())) {
                        Score score1 = mapping.get(score.getUid());
                        score1.setScore(score1.getScore() + score.getScore());
                    } else {
                        mapping.put(score.getUid(), score);
                    }
                }
            }catch (Exception e){
                log.error("获取历史分数错误", e);
            }
        }
        if ( result.isEmpty()){
            //如果没有数据则写死两个
            Score score=new Score();
            score.setUid(314948034l);
            score.setScore(0.0);
            score.setName("牟孝杨");
            score.setTaskGroupName("一组");
            result.add(score);
            Score score1=new Score();
            score1.setUid(396655720l);
            score1.setScore(0.0);
            score1.setName("谭春勇");
            score1.setTaskGroupName("二组");
            result.add(score1);
        }
        return mapping.values().stream().sorted(Comparator.comparing(Score::getScore)).collect(Collectors.toList());
    }

    public List<Score> getAllScore(Long activeId, Long classId) throws Exception {
        // 获取另一个系统的班级id
        String anotherClassId = getAnotherSystemId(classId);
        // 获取另一个系统的课程id
        String anotherCourseId = getAnotherCourseId(anotherClassId);
        // 获取另一个系统的分数
        List<AnotherScore> anotherScoresList = getAnotherScore(anotherCourseId);
        Map<String, Double> anotherMap = anotherScoresList.stream().collect(Collectors.toMap(a -> a.getUsername(), a -> a.getScore(), (a1, a2) -> a1));


        List<Score> result = new ArrayList<>();
        Request request = new Request.Builder()
                .url("https://mobilelearn.chaoxing.com/v2/apis/task/getAllMembersByActiveId?activeId=" + activeId)
                .build();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("allGroupMembers");
            for(int i = 0; i < jsonArray.size(); i ++){
                Score score = jsonArray.getJSONObject(i).toJavaObject(Score.class);
                Double orDefault = anotherMap.getOrDefault(score.getName(), 0.0);
                if(score.getScore() == null){
                    score.setScore(orDefault / 2);
                } else {
                    score.setScore((orDefault + score.getScore()) / 2);
                }
                result.add(score);
            }
        }catch (Exception e){
            throw new Exception("获取分数失败");
        }
        return result;
    }

    private List<AnotherScore> getAnotherScore(String anotherCourseId) throws Exception {
        List<AnotherScore> result = new ArrayList<>();
        Request request = new Request.Builder()
                .url("https://ps-training.fuchuan.host/api/admin/courseStudent?current=1&pageSize=200&courseId=" + anotherCourseId +"&sort=%7B%7D")
                .header("Authorization", "Bearer " + GlobalConfig.globalToken)
                .build();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                AnotherScore build = new AnotherScore().builder()
                        .score(tmp.getDouble("score"))
                        .username(tmp.getJSONObject("student").getString("name")).build();
                result.add(build);
            }
        }catch (Exception e){
            throw new Exception("获取分数失败");
        }


        return result;
    }

    private String getAnotherCourseId(String anotherClassId) {

        // https://ps-training.fuchuan.host/api/admin/course?current=1&pageSize=20&classId=xk_JBTYdCdfB8_nGczz8G&sort=%7B%7D
        Request request = new Request.Builder()
                .url("https://ps-training.fuchuan.host/api/admin/course?current=1&pageSize=100&classId=" + anotherClassId + "&sort=%7B%7D")
                .get()
                .header("Authorization", "Bearer " + GlobalConfig.globalToken)
                .build();
        try(Response response = anotherClient.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            JSONArray list = jsonObject.getJSONArray("list");
            for(int i = 0; i < list.size(); i ++){
                JSONObject tmp = list.getJSONObject(i);
                if(tmp.getString("status").equals("Open")){
                    return tmp.getString("id");
                }
            }
        }catch (Exception e){
            throw new RuntimeException("获取列表错误");
        }
        return "";
    }

    private String getAnotherSystemId(Long classId) {
        String className = "";
        for(Map.Entry<String, Long> entry : GlobalConfig.getClassMapping().entrySet()){
            if(entry.getValue().equals(classId) ){
                className = entry.getKey();break;
            }
        }
        Request request = new Request.Builder()
                .url("https://ps-training.fuchuan.host/api/admin/class?current=1&pageSize=1000&sort=%7B%7D")
                .get()
                .header("Authorization", "Bearer " + GlobalConfig.globalToken)
                .build();
        try(Response response = anotherClient.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            JSONArray list = jsonObject.getJSONArray("list");
            for(int i = 0; i < list.size(); i ++){
                JSONObject tmp = list.getJSONObject(i);
                if(tmp.getString("name").equals(className)){
                    return tmp.getString("id");
                }
            }
        }catch (Exception e){
            throw new RuntimeException("获取列表错误");
        }
        return "";
    }

    /**
     * 获取课程成绩
     *
     * */
    public ClassScoreAvg getClassScore(Long courseId,Long classId) throws Exception {
        ClassScoreAvg result=new ClassScoreAvg();
        Request request = new Request.Builder()
                .url("https://mooc1.chaoxing.com/mooc-ans/work/count/workcountdetail?courseId="+courseId+"&classId="+classId)
                .get()
                .build();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            List<Double> avgWorkScore = new ArrayList<>();
            JSONArray jsonArray = jsonObject.getJSONArray("workScoreCountArr");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                Double avgWorkScore1 = tmp.getDouble("avgWorkScore");
                avgWorkScore.add(avgWorkScore1);
            }
            result.setAvgWorkScore(avgWorkScore);
            List<String> workPostCountArr = new ArrayList<>();
            jsonArray = jsonObject.getJSONArray("workPostCountArr");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                String avgWorkScore1 = tmp.getString("title");
                workPostCountArr.add(avgWorkScore1);
            }
            result.setWorkPostCountArr(workPostCountArr);
        }catch (Exception e){
            log.info("获取分数失败原因{}",e);
            result.setWorkPostCountArr( GlobalConfig.getWorkPostCountArr());
            result.setAvgWorkScore(Collections.nCopies(10, 0.0)); // 创建一个长度为7且元素全为0.0的列表作为平均工作评分
            return result;
        }


        return result;
    }

    /**
     * 获取课程成绩
     *
     * */
    public Map<String,Double> getClassSchedule(Long courseId,Long classId,Long cpi) throws Exception {
        Request request = new Request.Builder()
                .url("https://stat2-ans.chaoxing.com/stat2/task/chapter/job-data?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=t&pEnc=&chapters=&page=1&pageSize=16")
                .get()
                .build();
        Map<String,Double> map=new HashMap<>();
        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            JSONObject jsonObject = JSON.parseObject(string);
            Integer  stuNum= jsonObject.getJSONObject("data").getInteger("stuNum");
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("chapterList");
            Integer chapter=1;//章节数
            Integer avgWorkScore=0;
            String tmpName = jsonArray.getJSONObject(0).getString("name");
            for(int i = 0; i < jsonArray.size(); i ++){
                JSONObject tmp = jsonArray.getJSONObject(i);
                String label = tmp.getString("label").substring(0, 1);
                if  (label.equals(chapter.toString())){
                    avgWorkScore=avgWorkScore+(tmp.getInteger("progress"));
                }else{
                    map.put(tmpName,(avgWorkScore*0.5)/stuNum);
                    chapter++;
                    avgWorkScore=0;
                    avgWorkScore=avgWorkScore+(tmp.getInteger("progress"));
                    tmpName=tmp.getString("name");
                }
            }
            JSONObject pageInfo =  jsonObject.getJSONObject("data").getJSONObject("pageInfo");
            for (int i=2;i<=pageInfo.getInteger("totalPage");i++){
                Request  request1 = new Request.Builder()
                        .url("https://stat2-ans.chaoxing.com/stat2/task/chapter/job-data?clazzid="+classId+"&courseid="+courseId+"&cpi="+cpi+"&ut=t&pEnc=&chapters=&page="+i+"&pageSize=16")
                        .get()
                        .build();
                try(Response Response1 = client.newCall(request1).execute()) {
                    string = Response1.body().string();
                    log.info("response:{}",string);
                    jsonObject = JSON.parseObject(string);
                    jsonArray = jsonObject.getJSONObject("data").getJSONArray("chapterList");

                    for(int j = 0; j < jsonArray.size(); j ++){
                        JSONObject tmp = jsonArray.getJSONObject(j);
                        String label = tmp.getString("label").substring(0, 1);
                        if  (label.equals(chapter.toString())){
                            avgWorkScore=avgWorkScore+(tmp.getInteger("progress"));
                        }else{
                            map.put(tmpName,(avgWorkScore*0.5)/stuNum);
                            chapter++;
                            avgWorkScore=0;
                            avgWorkScore=avgWorkScore+(tmp.getInteger("progress"));
                            tmpName=tmp.getString("name");

                        }
                    }
                }catch (Exception e){
                    log.info("错误为{}",e);
//            throw new Exception("获取分数失败");
                    return null;
                }
            }
            map.put(tmpName,(avgWorkScore*0.5)/stuNum);
        }catch (Exception e){
            List<String> workPostCountArr = GlobalConfig.getWorkPostCountArr();
            for (String s:
            workPostCountArr) {
                map.put(s,0.0);
            }
            log.info("获取分数失败错误为{}",e);
            return map;
        }
        return map;
    }

    public List<GroupScore> getGroupScore(HistoryScore historyScore) throws Exception {
        List<Score> scoreList = getHistoryScore(historyScore);
        Map<String, GroupScore> mapping = new HashMap<>();
        Map<String, Integer> count = new HashMap<>();
        for(Score score : scoreList){
            if(mapping.containsKey(score.getTaskGroupName())){
                GroupScore groupScore = mapping.get(score.getTaskGroupName());
                groupScore.setScore(groupScore.getScore() + score.getScore().intValue());
                count.put(score.getTaskGroupName(), count.get(score.getTaskGroupName()) + 1);
            } else {
                GroupScore groupScore = new GroupScore();
                groupScore.setGroupname(score.getTaskGroupName());
                groupScore.setScore(score.getScore().intValue());
                mapping.put(score.getTaskGroupName(), groupScore);
                count.put(score.getTaskGroupName(), 1);
            }
        }
        return mapping.values().stream().sorted(Comparator.comparing(GroupScore::getScore).reversed()).collect(Collectors.toList());
    }



    public static void main(String[] args) throws IOException {
        //Boolean andStoreCookies = getAndStoreCookies(null);



        RequestBody formBody = new FormBody.Builder()
                .add("sw", "")
                .add("workId", "27492201")
                .add("courseId", "231182970")
                .add("pageNum", "3")
                .add("classId", "74784084")
                .add("isdisplaytable", "2")
                .add("isWork", "true")
                .add("tempClassId", "74784084")
                .add("dengji", "0")
                .add("firstHeader", "2")
                .add("schoolId", "-1")
                .add("schoolName", "")
                .add("sort", "-1")
                .add("order", "")
                .add("workSystem", "0")
                .add("openc", "da8cb23e928cca42761f9887808c3df4")
                .build();

        Request request = new Request.Builder()
                .url("https://mooc1-1.chaoxing.com/work/searchMarkList")
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            System.out.println(responseBody);
        }
    }
}
